from django.contrib import admin
from .models import Role, UserProfile, SystemConfig, OperationLog


@admin.register(Role)
class RoleAdmin(admin.ModelAdmin):
    list_display = ['name', 'is_active', 'user_count', 'created_at', 'updated_at']
    list_filter = ['is_active', 'created_at']
    search_fields = ['name', 'description']
    
    def user_count(self, obj):
        return obj.userprofile_set.count()
    user_count.short_description = '用户数量'


@admin.register(UserProfile)
class UserProfileAdmin(admin.ModelAdmin):
    list_display = ['user', 'role', 'phone', 'department', 'position', 'is_active', 'created_at']
    list_filter = ['is_active', 'role', 'created_at']
    search_fields = ['user__username', 'phone', 'department', 'position']
    raw_id_fields = ['user', 'role']


@admin.register(SystemConfig)
class SystemConfigAdmin(admin.ModelAdmin):
    list_display = ['key', 'config_type', 'is_public', 'description', 'created_at', 'updated_at']
    list_filter = ['config_type', 'is_public', 'created_at']
    search_fields = ['key', 'description']


@admin.register(OperationLog)
class OperationLogAdmin(admin.ModelAdmin):
    list_display = ['username', 'log_type', 'module', 'action', 'ip_address', 'result', 'created_at']
    list_filter = ['log_type', 'module', 'result', 'created_at']
    search_fields = ['username', 'action', 'module']
    readonly_fields = ['user', 'username', 'log_type', 'module', 'action', 'ip_address', 
                      'user_agent', 'result', 'error_message', 'created_at']
    
    def has_add_permission(self, request):
        return False
    
    def has_change_permission(self, request, obj=None):
        return False
